import PySimpleGUI as sg
from common.config import *
from common.taskmgr import TaskMgr
from engine.task_runner import TaskRunner
from .mpl_mgr import MplMgr
from engine.qlib_utils import qlib_data

class EventHandler:
    def __init__(self, win: sg.Window):
        self.win = win
        self.key_2_handler = {
            '更新指数' : self.update_index,
            '打开Config目录':self.open_config,
            '编辑任务':self.update_task,
            '运行任务':self.run_task,
            '分析': self.analysis,
            '-TASK-FINISHED-':self.task_done,
            'dump csv到qlib格式':self.dump_csv,
            '_table_': self.click_table,
        }

    def process(self, event, values):
        if event in self.key_2_handler.keys():
            self.key_2_handler[event](values)
        else:
            print('事件未定义',event)

    def click_table(self, values):
        table = self.win['_table_']
        rows = table.SelectedRows
        if len(rows):
            code = table.Values[rows[0]][0]
            print(code)

    def dump_csv(self, values):
        folder = sg.PopupGetFolder('请选择CSV所在目录：')
        target_folder = sg.PopupGetText('请输入目标目录名：')
        qlib_data.dump_csv(path=folder,target_folder=target_folder)

    def task_done(self, values):
        sg.Popup('任务完成！')

    def load_tasks(self):
        self.win['-TASKS-'].update(TaskMgr().get_task_list().keys())

    def update_index(self, values):
        sg.Popup('更新指数')

    def update_task(self, values):
        if '-TASKS-' not in values or len(values['-TASKS-'])==0:
            sg.Popup('请选择要编辑的任务！')
            return
        task_name = values['-TASKS-'][0]
        task = TaskMgr().get_task(task_name)
        print(task)


    def analysis(self, values):
        print(values)
        start = values['-START-']
        end = values['-END-']
        benchs = values['-BENCH-']
        tasks = values['-RESULTS-']
        df_equities, df_ratios, df_corr, df_years = TaskRunner.analysis(start=start,end=end,benchmarks=benchs,task_names=tasks)
        print(df_ratios)
        print(df_ratios.to_string())
        self.win['-OUT-'].update(df_ratios.to_string())
        df_ratios['策略名称'] = df_ratios.index

        cols = ['策略名称','累计收益','年化收益','夏普比','最大回撤','年化收益与最大回撤比','波动率']
        df_ratios= df_ratios[cols]
        #self.win['-RATIO-'].update(headings=cols)
        self.win['-RATIO-'].update(df_ratios.values)
        MplMgr().show_graph({'equity': df_equities, 'yearly': df_years, 'ratio':df_ratios,'corr':df_corr})

    def run_task_(self, values):
        print('运行任务...',values)
        task_name = values['-TASKS-']
        task = T.get_task(task_name)
        print(task)
        TaskRunner().run(task)


    def run_task(self, values):
        if '-TASKS-' not in values or len(values['-TASKS-']) == 0:
            sg.Popup('请选择要运行的任务！')
            return

        self.win.perform_long_operation(lambda: self.run_task_(values), '-TASK-FINISHED-')


    def open_config(self, values):
        import os
        print(get_config_path())
        try:
            from os import startfile
            startfile(get_config_path())
        except:
            print('open_config发生异常。')



